package com.aia.aia2.service;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

import com.aia.aia2.domain.Formdata;
import com.aia.aia2.domain.FormdataExt;
import com.aia.aia2.domain.Gpinsu;
import com.aia.aia2.domain.GpinsuExample;
import com.aia.aia2.web.group.Form1Action;
import com.aia.aia2.web.group.Form2Action;
import com.aia.aia2.web.group.Form3Action;
import com.aia.aia2.web.group.InsuActionSupport;
import com.aia.aia2.web.group.ResultAction;
import com.aia.aia2.web.json.GroupForm1Json;
import com.aia.aia2.web.json.GroupForm2Json;
import com.aia.aia2.web.json.GroupResultJson;
import com.aia.ilp.domain.SmsLog;
import com.aia.ilp.domain.SmsLogExample;
import com.aia.prm.config.AddressNotFoundException;
import com.aia.prm.config.ChinaAddress;
import com.aia.prm.config.CompanyCodes;
import com.aia.prm.service.AbstractDefaultService;
import com.aia.prm.service.ServiceResult;
import com.cfh.ahead.Constant;
import com.cfh.util.Myservice;
import com.cfh.util.Tools;

public class GroupService extends AbstractDefaultService implements Myservice {
	private static final Logger logger = Logger.getLogger(GroupService.class);

	public void updateGroupForm1(GroupForm1Json action) {
		logger.debug("Start counter");
		String gid = action.getFormdataExt().getGI_ID();
		// validate GI_ID
		Gpinsu gpinsu = gpinsuDAO.selectByPrimaryKey(gid);
		if (gpinsu == null) {
			action.addActionError("找不到对应的产品记录");
			return;
		}
		// 得到产品
		FormdataExt formdata = action.getFormdataExt();
		formdata.setGI_PARENT(gpinsu.getGI_PARENT());
		formdata.setGI_NAME(gpinsu.getGI_NAME());
		formdata.setGI_SHORT(gpinsu.getGI_SHORT());
		formdata.setGI_ARGUMENTS(gpinsu.getGI_ARGUMENTS());
		formdata.setGI_VERSION(gpinsu.getGI_VERSION());
		formdata.setFD_GUID(Tools.GUID());
		formdata.setFD_DATE(Tools.getToday());
		formdata.setFD_TIME(Tools.getTime());
		formdata.setFD_IP(Tools.makeIPAddress());
		Counter counter = new Counter(formdata, gpinsu);
		try {
			counter.count();
		} catch (CounterException e) {
			logger.warn("计算出错：" + e.getMessage());
			action.addActionError(e.getMessage());
			return;
		} catch (RuntimeException e) {
			logger.error("计算出错：" + e, e);
			action.addActionError("服务器内部错误:" + e.getMessage());
			return;
		}
		formdataDAO.insert(formdata);
	}

	public void form1Action(Form1Action action) {
		readyInsuList(action);
		// fetch data from db
		Gpinsu gpinsu = gpinsuDAO.selectByPrimaryKey(action.getPid());
		if (gpinsu == null) {
			action.addActionError("找不到对应的产品记录");
			return;
		}
		action.setGpinsu(gpinsu);
	}

	@SuppressWarnings("rawtypes")
	private void readyInsuList(InsuActionSupport action) {
		GpinsuExample example = new GpinsuExample();
		example.setOrderByClause("GI_ORDER");
		List insuList = gpinsuDAO.selectByExample(example);
		action.setInsuList(insuList);
	}

	public void form2Action(Form2Action action) {
		readyInsuList(action);
		// 1. get formdata
		String rid = action.getRid();
		Formdata formdata = formdataDAO.selectByPrimaryKey(rid);
		if (formdata == null) {
			action.addActionError("没有该记录");
			return;
		}
		action.setFormdata(formdata);
		// 2. get gpinsu
		Gpinsu gpinsu = gpinsuDAO.selectByPrimaryKey(formdata.getGI_ID());
		action.setGpinsu(gpinsu);
	}

	@SuppressWarnings("rawtypes")
	public void updateGroupForm2(GroupForm2Json action) {
		String rid = action.getRid();
		Formdata fd = formdataDAO.selectByPrimaryKey(rid);
		if (fd == null) {
			action.addActionError("找不到记录");
			return;
		}
		if (Tools.hasText(fd.getFD_PHONE())) {
			action.addActionError("已经计算过了，请选择产品重新计算");
			return;
		}
		final Formdata lms = action.getFormdataExt();
		{
			// 校验手机验证码
			final String code = lms.getFD_FREETEXT1();
			final String mobile = lms.getFD_PHONE();
			if (!Tools.hasText(code)) {
				action.addActionError("验证码为空");
				return;
			}

			if (!Tools.hasText(mobile)) {
				action.addActionError("手机号为空");
				return;
			}
			String powerKey = Tools.getProperties("sms.powerkey");
			if (code.equalsIgnoreCase(powerKey)) {
				logger.info("使用了超级验证码来验证");
				lms.setFD_FREEFLAG2("Y");
			} else {
				lms.setFD_FREEFLAG2("N");
				SmsLogExample example = new SmsLogExample();
				example.createCriteria().andSMSLOG_DATEEqualTo(Tools.getToday()).andSMSLOG_MOBILEEqualTo(mobile)
						.andSMSLOG_FREETEXT1EqualTo(code).andSMSLOG_FREETEXT2NotEqualTo("Y");
				example.or(example.createCriteria().andSMSLOG_DATEEqualTo(Tools.getToday()).andSMSLOG_MOBILEEqualTo(mobile)
						.andSMSLOG_FREETEXT1EqualTo(code).andSMSLOG_FREETEXT2IsNull());
				List list = smsLogDAO.selectByExample(example);
				if (list == null || list.size() == 0) {
					action.addActionError("验证码错误，可能是验证码过期，请尝试重新获取验证码");
					return;
				} else {// 如果发现验证码对了，那么将这个验证码即时做废，也就是让 SMSLOG_FREETEXT2=Y
					try {
						for (Iterator iterator = list.iterator(); iterator.hasNext();) {
							Object object = (Object) iterator.next();
							SmsLog item = (SmsLog) object;
							SmsLog toUpdate = new SmsLog();
							toUpdate.setSMSLOG_FREETEXT2("Y");
							toUpdate.setSMSLOG_GUID(item.getSMSLOG_GUID());
							smsLogDAO.updateByPrimaryKeySelective(toUpdate);
						}
					} catch (Exception e) {
						logger.warn("修改表smsLog出错", e);
					}
				}
			}
		}
		action.setOutputRid(fd.getFD_GUID());

		Formdata input = action.getFormdataExt();
		input.setFD_GUID(fd.getFD_GUID());
		fd.setFD_COMPANY(input.getFD_COMPANY());
		fd.setFD_NAME(input.getFD_NAME());
		fd.setFD_SEX(input.getFD_SEX());
		fd.setFD_SERVICE(input.getFD_SERVICE());
		fd.setFD_ADDRESS(input.getFD_ADDRESS());
		fd.setFD_PROVINCE(input.getFD_PROVINCE());
		fd.setFD_CITY(input.getFD_CITY());
		fd.setFD_DISTRICT(input.getFD_DISTRICT());
		fd.setFD_PHONE(input.getFD_PHONE());
		fd.setFD_TEL(input.getFD_TEL());
		fd.setFD_FREEFLAG2(input.getFD_FREEFLAG2()); // 使用了超级验证码来验证?
		updateDistCode(fd);

		String code = "05";
		String msg = "计算成功，等待发送";
		fd.setFD_UNICA_FLAG("N");
		fd.setFD_UNICA_CODE(code);
		fd.setFD_UNICA_REMARK(msg);

		formdataDAO.updateByPrimaryKey(fd);
		// 不发送，用户要在网页上手动发送
		// ServiceResult result = sendFormdataLms(fd);

	}

	/**
	 * 只有省市，没有区, 需要补上默认的区
	 * 
	 * @param fd
	 */
	private void updateDistCode(Formdata fd) {
		ChinaAddress address = null;
		try {
			address = CompanyCodes.translateToAddressNew(fd.getFD_PROVINCE(), fd.getFD_CITY());
			if (address != null) {
				if (!Tools.hasText(fd.getFD_DISTRICT())) {
					fd.setFD_DISTRICT(address.getDistCode());
				}
				fd.setFD_COMPANY_CODE(address.getCompanyCode());
			}
		} catch (AddressNotFoundException e) {
			logger.error(e);
		}
	}

	public ServiceResult sendFormdataLms(Formdata lookup) {
		ServiceResult result = new ServiceResult();
		try {
			String tmplate = makeFormdataLmsTmplate(lookup);
			logger.debug("****************  PRINT LMS REQUEST START  ****************");
			logger.debug(tmplate);
			logger.debug("****************  PRINT LMS REQUEST END    ****************");

			if ("dev".equalsIgnoreCase(Tools.getProperties("website.evn"))) {
				String code = "01";
				String msg = "测试环境下跳过LMS接口";
				result.setCode(code);
				result.setErrorMsg(msg);
				lookup.setFD_UNICA_FLAG("N");
				lookup.setFD_UNICA_CODE(code);
				lookup.setFD_UNICA_REMARK(msg);
				formdataDAO.updateByPrimaryKey(lookup);
				return result;
			} else {

				// 开始发送
				logger.debug(">>>>>>>>>>> Send LMS start");
				HttpURLConnection connection = null;
				String endpoint = Tools.getDatabaseProperty("service", "address_lms");
				logger.debug("LMS endpoint=" + endpoint);
				long beforeTime = System.currentTimeMillis();
				connection = (HttpURLConnection) new URL(endpoint).openConnection();
				connection.setDoOutput(true);
				connection.setDoInput(true);
				connection.setRequestMethod("POST");
				connection.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
				connection.setRequestProperty("soapaction", "");
				connection.setConnectTimeout(5000);
				connection.setReadTimeout(5000);
				connection.connect();
				OutputStream os = connection.getOutputStream();
				os.write(tmplate.getBytes("UTF-8"));
				os.flush();
				os.close();
				InputStream is = connection.getInputStream();// 获取数据，真正的请求从此处开始
				byte[] bts = new byte[is.available()];
				is.read(bts);
				String returnString = new String(bts, "UTF-8");
				long afterTime = System.currentTimeMillis();
				logger.debug("LMS成功返回！耗时:" + (afterTime - beforeTime) + "ms");
				logger.debug("%%%%%%%%%%%%%%%%  PRINT LMS RESPONSE START  %%%%%%%%%%%%%%%%");
				logger.debug(returnString);
				logger.debug("%%%%%%%%%%%%%%%%  PRINT LMS RESPONSE END    %%%%%%%%%%%%%%%%");

				String code = "00";
				String msg = "成功";
				result.setCode(code);
				result.setErrorMsg(msg);

				lookup.setFD_UNICA_FLAG("Y");
				lookup.setFD_UNICA_CODE(code);
				lookup.setFD_UNICA_REMARK(msg);
				if (returnString.length() > 1500) {
					returnString = returnString.substring(0, 1500);
				}
				lookup.setFD_UNICA_RESPONSE(returnString);

				formdataDAO.updateByPrimaryKey(lookup);
				return result;
			}
		} catch (Throwable e) {
			String msgLong = "LMS接口调用失败:" + e;
			logger.error(msgLong, e);
			String msgShort = msgLong;
			if (msgShort.length() > 200) {
				msgShort = msgShort.substring(0, 200) + "..";
			}
			String code = "99";
			String msg = msgShort;
			result.setCode(code);
			result.setErrorMsg(msg);
			lookup.setFD_UNICA_FLAG("N");
			lookup.setFD_UNICA_CODE(code);
			lookup.setFD_UNICA_REMARK(msg);
			formdataDAO.updateByPrimaryKey(lookup);
			return result;
		}
	}

	public String makeFormdataLmsTmplate(Formdata lookup) {
		String tmplate = "";
		try {
			tmplate = IOUtils.toString(this.getClass().getResourceAsStream("/conf/lms_formdata.xml"), "UTF-8");
		} catch (IOException e) {
			logger.error("Cannot read classpath file: /conf/lms_formdata.xml", e);
			throw new RuntimeException(e);
		}
		final String campaign = Tools.getDatabaseProperty("service", "group_campaign");
		final String agent = Tools.getDatabaseProperty("service", "group_agent");

		tmplate = tmplate.replaceAll("\\$\\{campaign\\}", Tools.trimStr(campaign));
		tmplate = tmplate.replaceAll("\\$\\{Agent\\}", Tools.trimStr(agent));
		String sex = "M";
		if ("女".equals(lookup.getFD_SEX())) {
			sex = "F";
		}
		tmplate = tmplate.replaceAll("\\$\\{LMS_BB_SEX\\}", sex);
		tmplate = tmplate.replaceAll("\\$\\{LMS_MOBILE\\}", Tools.trimStr(lookup.getFD_PHONE()));
		tmplate = tmplate.replaceAll("\\$\\{LMS_BB_CITY\\}", lookup.getFD_CITY());
		tmplate = tmplate.replaceAll("\\$\\{LMS_BB_PROVINCE\\}", lookup.getFD_PROVINCE());
		tmplate = tmplate.replaceAll("\\$\\{LMS_BB_DISTRICT\\}", lookup.getFD_DISTRICT());
		String name = lookup.getFD_NAME();
		String firstname = "";
		String lastname = "";
		if (Tools.hasText(name)) {
			lastname = name.substring(0, 1);
			if (name.length() >= 2) {
				firstname = name.substring(1);
			}
		}
		tmplate = tmplate.replaceAll("\\$\\{firstname\\}", firstname);
		tmplate = tmplate.replaceAll("\\$\\{lastname\\}", lastname);

		String birthyear = "";
		tmplate = tmplate.replaceAll("\\$\\{Birthyear\\}", birthyear);
		tmplate = tmplate.replaceAll("\\$\\{Marriage\\}", "");

		String tempTodayStr = "";
		{
			SimpleDateFormat formatter = new SimpleDateFormat("MM/dd");
			tempTodayStr = formatter.format(new Date());
		}

		String description1 = "";
		if (lookup.getFD_RESULT() != null && lookup.getFD_RESULT() > 0) {
			// - 日期 城市 试算产品/计划 公司名称 公司人数 保费
			// - 举例： 07/03 上海用户 试算团险盛安经济型计划 友邦保险公司 100人 首年保费62700
			description1 = tempTodayStr + " " + lookup.getFD_PROVINCE() + "用户 试算" + lookup.getGI_SHORT() + " " + lookup.getFD_COMPANY()
					+ " " + lookup.getFD_COUNT() + "人 首年保费" + lookup.getFD_RESULT();
		} else {
			// - 日期 城市 试算团险保费 公司名称 公司人数 要求直接联系营销员
			// - 举例： 07/03 上海用户 试算团险保费 友邦保险公司 100人 要求直接联系营销员
			description1 = tempTodayStr + " " + lookup.getFD_PROVINCE() + "用户 试算团险保费 " + lookup.getFD_COMPANY() + " 要求直接联系营销员";

		}

		tmplate = tmplate.replaceAll("\\$\\{Description1\\}", description1);
		tmplate = tmplate.replaceAll("\\$\\{companyCode\\}", lookup.getFD_COMPANY_CODE());
		return tmplate;
	}

	public void resultAction(ResultAction action) {
		readyInsuList(action);
		// 1. get formdata
		String rid = action.getRid();
		Formdata formdata = formdataDAO.selectByPrimaryKey(rid);
		if (Tools.isEmpty(formdata.getFD_PHONE())) {
			action.addActionError("Invalid access, phone number is empty!");
			return;
		}
		action.setFormdata(formdata);
		// 2. get gpinsu
		Gpinsu gpinsu = gpinsuDAO.selectByPrimaryKey(formdata.getGI_ID());
		action.setGpinsu(gpinsu);

	}

	public void form3Action(Form3Action action) {
		readyInsuList(action);
		// fetch data from db
		Gpinsu gpinsu = gpinsuDAO.selectByPrimaryKey(action.getPid());
		if (gpinsu == null) {
			action.addActionError("找不到对应的产品记录");
			return;
		}
		action.setGpinsu(gpinsu);
	}

	@SuppressWarnings("rawtypes")
	public void updateGroupForm3(GroupForm2Json action) {
		String gid = action.getFormdataExt().getGI_ID();
		// validate GI_ID
		Gpinsu gpinsu = gpinsuDAO.selectByPrimaryKey(gid);
		if (gpinsu == null) {
			action.addActionError("找不到对应的产品记录");
			return;
		}

		final Formdata lms = action.getFormdataExt();
		{
			// 校验手机验证码
			final String code = lms.getFD_FREETEXT1();
			final String mobile = lms.getFD_PHONE();
			if (!Tools.hasText(code)) {
				action.addActionError("验证码为空");
				return;
			}

			if (!Tools.hasText(mobile)) {
				action.addActionError("手机号为空");
				return;
			}
			String powerKey = Tools.getProperties("sms.powerkey");
			if (code.equalsIgnoreCase(powerKey)) {
				logger.info("使用了超级验证码来验证");
				lms.setFD_FREEFLAG2("Y");
			} else {
				lms.setFD_FREEFLAG2("N");
				SmsLogExample example = new SmsLogExample();
				example.createCriteria().andSMSLOG_DATEEqualTo(Tools.getToday()).andSMSLOG_MOBILEEqualTo(mobile)
						.andSMSLOG_FREETEXT1EqualTo(code).andSMSLOG_FREETEXT2NotEqualTo("Y");
				example.or(example.createCriteria().andSMSLOG_DATEEqualTo(Tools.getToday()).andSMSLOG_MOBILEEqualTo(mobile)
						.andSMSLOG_FREETEXT1EqualTo(code).andSMSLOG_FREETEXT2IsNull());
				List list = smsLogDAO.selectByExample(example);
				if (list == null || list.size() == 0) {
					action.addActionError("验证码错误，可能是验证码过期，请尝试重新获取验证码");
					return;
				} else {// 如果发现验证码对了，那么将这个验证码即时做废，也就是让 SMSLOG_FREETEXT2=Y
					try {
						for (Iterator iterator = list.iterator(); iterator.hasNext();) {
							Object object = (Object) iterator.next();
							SmsLog item = (SmsLog) object;
							SmsLog toUpdate = new SmsLog();
							toUpdate.setSMSLOG_FREETEXT2("Y");
							toUpdate.setSMSLOG_GUID(item.getSMSLOG_GUID());
							smsLogDAO.updateByPrimaryKeySelective(toUpdate);
						}
					} catch (Exception e) {
						logger.warn("修改表smsLog出错", e);
					}
				}
			}
		}
		Formdata fd = new Formdata();
		action.setOutputRid(fd.getFD_GUID());
		Formdata input = action.getFormdataExt();

		// 得到产品
		fd.setGI_PARENT(gpinsu.getGI_PARENT());
		fd.setGI_NAME(gpinsu.getGI_NAME());
		fd.setGI_ARGUMENTS(gpinsu.getGI_ARGUMENTS());
		fd.setGI_VERSION(gpinsu.getGI_VERSION());
		fd.setFD_DATE(Tools.getToday());
		fd.setFD_TIME(Tools.getTime());
		fd.setFD_IP(Tools.makeIPAddress());
		fd.setFD_GUID(Tools.GUID());
		fd.setGI_ID(input.getGI_ID());
		fd.setFD_COMPANY(input.getFD_COMPANY());
		fd.setFD_NAME(input.getFD_NAME());
		fd.setFD_SEX(input.getFD_SEX());
		fd.setFD_SERVICE(input.getFD_SERVICE());
		fd.setFD_ADDRESS(input.getFD_ADDRESS());
		fd.setFD_PROVINCE(input.getFD_PROVINCE());
		fd.setFD_CITY(input.getFD_CITY());
		fd.setFD_DISTRICT(input.getFD_DISTRICT());
		fd.setFD_PHONE(input.getFD_PHONE());
		fd.setFD_TEL(input.getFD_TEL());
		fd.setFD_FREEFLAG2(input.getFD_FREEFLAG2());// 使用了超级验证码来验证?
		fd.setFD_FREEFLAG1("Y");// 要求营销员联系?
		updateDistCode(fd);
		formdataDAO.insert(fd);
		sendFormdataLms(fd);
	}

	public void updateGroupResult(GroupResultJson action) {
		final String guid = action.getGuid();
		Formdata lookup = null;

		{// 校验非空
			if (!Tools.hasText(guid)) {
				action.addActionError("系统出错了，传入的参数为空");
				return;
			}
		}

		{// 校验是否已经手机激活LMS记录了
			lookup = formdataDAO.selectByPrimaryKey(guid);
			if (lookup == null) {
				action.addActionError("不存在该记录，请检查页面参数");
				return;
			}
			if (Constant.Y.equalsIgnoreCase(lookup.getFD_FREEFLAG1())) {
				action.addActionError("您之前已经提交过个人的信息，我们将会尽快安排营销员与您联系。");
				return;
			}
		}

		{// 更新lookup到数据库
			lookup.setFD_FREEFLAG1("Y");
			formdataDAO.updateByPrimaryKey(lookup);
		}

		sendFormdataLms(lookup);
	}

}
